package org.sun.web.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil {
	
	private static final Logger logger=LoggerFactory.getLogger(FileUtil.class);

	public static void writeFile(File file,String json){
		FileOutputStream fos=null;
		try {
			if(!file.exists())file.createNewFile();
			fos=new FileOutputStream(file);
			fos.write(chgStrToByt(json));
		} catch (FileNotFoundException e) {
			logger.error("没有找到文件"+file.getName(), e);
		} catch (IOException e) {
			logger.error("文件写入异常"+file.getName(), e);
		}finally{
			if(fos!=null)
				try {
					fos.close();
				} catch (IOException e) {
					logger.error("输出流关闭异常"+file.getName(), e);
				}
		}
	}
	public static void writeFile(String fileName,String json){
		if(fileName==null)return;
		File file=new File(fileName);
		writeFile(file, json);
	}
	public static String readFile(File file){
		String json="";
		FileInputStream fis=null;
		try {
			if(!file.exists())
				file.createNewFile();
			
			fis=new FileInputStream(file);
			byte[] b=new byte[1024];
			int isRead=fis.read(b);
			while(isRead>=0){
				json+=new String(b,"GBK");
				isRead=fis.read(b);
			}
		} catch (FileNotFoundException e) {
			logger.error("没有找到文件"+file.getName(), e);
		} catch (UnsupportedEncodingException e) {
			logger.error("不支持的编码异常", e);
		} catch (IOException e) {
			logger.error("IO异常", e);
		}finally{
			if(fis!=null)
				try {
					fis.close();
				} catch (IOException e) {
					logger.error("IO异常", e);
				}
		}
		return json;
	}
	public static String readFile(String fileName){
		File file=new File(fileName);
		String json=readFile(file);
		return json;
	}
	public static byte[] chgStrToByt(String json){
		byte[] b=json.getBytes();
		return b;
	}
}
